package com.lagou.rpc.consumer;

import com.lagou.rpc.consumer.client.RpcClient;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Desc
 * @Author Matures
 * @CreateTime 2021/4/11 10:45
 **/
public class ClientBootStrapZookeeper {

    private static Map<String, RpcClient> maps = new HashMap<>();

    private static final String path = "/lg-rpc";

    private static List<String> children = new ArrayList<>();


    public static void main(String[] args) throws InterruptedException {
        // 从zookeeper中获取所有服务端节点信息
        ZkClient zkClient = new ZkClient("127.0.0.1:2181");
        // 当前所有的子节点列表
        children = zkClient.getChildren(path);
        for (String child : children) {
            Object data = zkClient.readData(path+"/"+child);
            createConnect(child,data);
        }
        // 注册监听事件
        zkClient.subscribeChildChanges(path, new IZkChildListener() {
            @Override
            public void handleChildChange(String s, List<String> list) throws Exception {
                // list 为发生变化后的所有子节点列表
                // 当前没有的节点，现在有了就创建新的连接，当前有的现在没有了，则关闭连接
                for (String node : list) {
                    // 原来没有，新建连接
                    if(!children.contains(node)){
                        Object data = zkClient.readData(path+"/"+node);
                        createConnect(node,data);
                        children.add(node);
                    }
                }

                //原来有现在没有
                for (String child : children) {
                    // 关闭连接
                    if(!list.contains(child)){
                        closeConnect(child);
                        children.remove(child);
                    }
                }
            }
        });
        Thread.sleep(Integer.MAX_VALUE);


    }

    public static void createConnect(String path,Object data){
        String port = data.toString().split(":")[1];
        RpcClient rpcClient = new RpcClient("127.0.0.1", Integer.parseInt(port));
        maps.put(path,rpcClient);

        System.out.println("客户端与："+path+"的连接已建立");
    }

    public static void closeConnect(String path){
        RpcClient rpcClient = maps.get(path);
        rpcClient.close();
        maps.remove(path);
        System.out.println("客户端与："+path+"的连接已关闭");
    }


}
